import Frame from "../frameNamespace";

export default class BundleManager extends Frame.ManagerBase {
    protected _managerName: string = "bundle管理";

    constructor() {
        super();

        this._Initialize();
    }

    private length: number = 0;

    //可获取自动加载的bundle列表
    private bundList: Frame.BundleList = {
        frameBundle: null,
        soundBundle: null,
        gameBundle: null,

        home: null,
        loadingPage:null
    }

    //需要自动预加载的bundle列表，请前往frameNamespace.BundleName添加对应项
    //请按bundle等级以及需要的先后顺序依次排列
    private bundleLoadList: string[] = [
        //等级：9
        "frameBundle",
        "soundBundle",
        "gameBundle",

        //等级：3
        "loadingPage",
        "home",
       
    ]

    _Initialize(): void {
        super._Initialize();

        for (const key in this.bundleLoadList) {
            this.length++;
        }
    }

    getLength() {
        return this.length;
    }

    get BundleList() {
        return this.bundList;
    }

    async loadAllBundle(cb?: () => void) {

        for (let i = 0; i < this.bundleLoadList.length; i++) {
            let path = this.bundleLoadList[i];
            this.bundList[path] = await this.loadOnceBundle(path, path);
            cb && cb();
            console.debug(path);// + " :", this.bundList[key]
        }
    }

    private loadOnceBundle(path: string, name: string) {
        return new Promise<cc.AssetManager.Bundle>((resolve, reject) => {
            let record: Record<string, any> = <Record<string, any>>{};
            cc.assetManager.loadBundle(path, record, (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    console.error("bundle (name:" + name + "path :" + path + ") 加载出错!!", err);
                    // console.log("record :", record);
                    cc.assetManager.loadBundle(path, record, (err: Error, bundle: cc.AssetManager.Bundle) => {
                        if (err) {
                            console.error("bundle (name:" + name + "path :" + path + ") 加载出错2!!", err);
                            // console.log("record :", record);
                            reject(null);
                            return;
                        }
                        // console.log("record :", record);
                        resolve(bundle);
                    });
                    // reject(null);
                    return;
                }
                // console.log("record :", record);
                resolve(bundle);
            });
        });
    }
}